package cool.taomu.toolkit.platform

import com.google.common.reflect.TypeToken
import com.google.gson.Gson
import com.google.inject.Key
import com.google.inject.TypeLiteral
import com.google.inject.name.Names
import cool.taomu.toolkit.Context
import cool.taomu.toolkit.TaomuConfigure
import cool.taomu.toolkit.TaomuGuice
import cool.taomu.toolkit.TaomuGuiceServiceLoader
import cool.taomu.toolkit.crypto.Base64
import cool.taomu.toolkit.platform.entity.MenuEntity
import cool.taomu.toolkit.platform.modules.PlatformModule
import cool.taomu.toolkit.platform.service.TaskService
import cool.taomu.toolkit.utils.FileTools
import java.util.List
import java.util.concurrent.TimeUnit
import org.apache.commons.io.IOUtils
import org.apache.commons.vfs2.FileSystemManager
import org.slf4j.LoggerFactory

class Application {
    val static LOG = LoggerFactory.getLogger(Application);

    def static main(String[] args) {
        FileTools.unpackWar(Application, #["static", "template", "config"]);
        entry();
        while (true) {
            try {
                TimeUnit.HOURS.sleep(24)
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.err.println("Thread interrupted");
                return;
            }
        }
    }

    def static void entry() {
        val TaomuConfigure config = new TaomuConfigure(new Base64())
        config.loadConfig
        val injector = TaomuGuice.createInjector(config, new PlatformModule())
        TaomuGuiceServiceLoader.loadIPlatform(injector, config)
        var context = injector.getInstance(Context);
        val injector2 = context.injectorSupplier.get()
        try(var fobject = injector2.getInstance(FileSystemManager).resolveFile("res://config/menu.json")) {
            var json = IOUtils.toString(fobject.content.inputStream, "UTF-8");
            var type = injector.getInstance(Key.get(TypeToken, Names.named("taomu.menu.type")))
            var mList = injector.getInstance(Key.get(new TypeLiteral<List<Object>>() {
            }, Names.named("taomu.menu.list")))
            mList.add(new Gson().fromJson(json, type.rawType));
            LOG.info("type:{}", mList)
            mList.sort([ o1, o2 |
                var m1 = o1 as MenuEntity
                var m2 = o2 as MenuEntity
                return m1.getId().compareTo(m2.getId());
            ])
        }
        context.executor.submit([
            injector2.getInstance(TaskService).execute;
        ])
    }

}
